package com.jiuzhou.surery.Controller;

import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.jiuzhou.surery.exception.StorageException;
import com.jiuzhou.surery.service.StorageService;

@RestController
@RequestMapping("/files")
public class FileUploadController {
    
    
    private final StorageService storageService;
    
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }




    @PostMapping("/upload")
    public Map<String, String> handleFileUpload(MultipartFile file) { 
        String filename = storageService.store(file);
        return Map.of("filename", filename, "message", "文件上传成功");
    }


    @ExceptionHandler(StorageException.class)
    public Map<String, String> handleStorageException(StorageException e) { 
        return Map.of("message", e.getMessage());
    }

    @GetMapping("/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) { 
        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity
        .ok()
        .header("Content-Type","image/" +filename.substring(filename.lastIndexOf(".") + 1))
        .body(file);
    }
}
